package middleware

import (
	"api/internal/types"
	"api/pkg"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type AutoTokenMiddleware struct {
}

func NewAutoTokenMiddleware() *AutoTokenMiddleware {
	return &AutoTokenMiddleware{}
}

func (m *AutoTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		fmt.Println("触发了中间件")

		token := r.Header.Get("token")
		if token == "" {
			response := &types.Response{
				Code: "10001",
				Msg:  "token is null",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
		}
		userid, err := pkg.ParseJwtToken(token)
		if err != nil {
			response := &types.Response{
				Code: "10002",
				Msg:  "token is invalid",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
		}

		// Passthrough to next handler if need
		ext := context.WithValue(r.Context(), "userid", userid)
		next(w, r.WithContext(ext))
	}
}
